<?php

namespace app\admin\controller\yalimedia;

use addons\yalimedia\library\AlibabaCloundHelper;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\controller\Backend;

/**
 * 素材管理
 * @icon fa fa-circle-o
 */
class Media extends Backend
{
    protected $noNeedRight = ["tree","upload_tree",'createUploadImage',"createUploadVideo","refreshUploadVideo"];
    public $type = ['2'=>'音频','3'=>'视频'];
    public function _initialize()
    {
        parent::_initialize();

        $yalimedia = get_addon_config('yalimedia');
        $config = $yalimedia['ali'];
        if(empty($config['accessKeyId']) || empty($config['accessKeySecret']) || empty($config['regionId'])){
            $this->error(__('请完善插件《课程点播》阿里云视频点播配置项'),'');
        }

    }

    public function index(){
        $type = $this->request->param('type',2);
        $search = $this->request->param('search');
        $categoryModel = new \app\admin\model\yalimedia\Category();
        if(!$category = $categoryModel->where(['type'=>$type])->find()){
            if(!$cateId = AlibabaCloundHelper::instance()->add_category($this->type[$type],0)){
                $this->error(__('同步阿里云失败，请稍候再试~'));
            }else{
                $categoryModel = new \app\admin\model\yalimedia\Category();
                $categoryModel->save([
                    'cateid'=>$cateId,
                    'type'=>$type
                ]);
            }
        }else{
            $cateId = $category['cateid'];
        }


        if ($this->request->isAjax())
        {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $cateid = $this->request->get("cateid",$cateId);
            switch($type){
                case "2":
                    $type_name = "audio";
                    break;
                case "3":
                    $type_name = "video";
                    break;

            }
            $match = "CateId=".$cateid;
            if($search){
                $match.=" and Title = '".$search."'";
            }

            $list = AlibabaCloundHelper::instance()->searchMedia($type_name,$match,($offset/$limit)+1,$limit);
            $total = empty($list->Total)?0:$list->Total;

            $list = empty($list->MediaList)?[]:$list->MediaList;

            foreach($list as &$v){
                switch ($v->MediaType){
                    case "audio":
                        $v->AudioTitle = $v->Audio->Title;
                        $v->Status = $v->Audio->Status;
                        $v->Size =  AlibabaCloundHelper::instance()->getFilesize(empty($v->Audio->Size)?0:$v->Audio->Size);
                        $v->CreationTime = date("Y-m-d H:i:s",strtotime($v->Audio->CreationTime));
                        break;
                    case "video":
                        $v->VideoTitle = $v->Video->Title;
                        $v->VideoId = $v->Video->VideoId;
                        $v->Status = $v->Video->Status;
                        $v->Size =  empty($v->Video->Size)?'':AlibabaCloundHelper::instance()->getFilesize(empty($v->Video->Size)?0:$v->Video->Size);
                        $v->CoverURL = empty($v->Video->CoverURL)?'':$v->Video->CoverURL;
                        $v->CreationTime = date("Y-m-d H:i:s",strtotime($v->Video->CreationTime));
                        break;
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }


        //查看当前是否已经生成根分类
        $list = AlibabaCloundHelper::instance()->categories($cateId);

        $chanelList[$cateId] = ['id'=>$cateId,'text'=>"全部视频",'num'=>0,'parent'=>"#",'state'=>['opened'=>true]];
        foreach($list as $k=>$v){
            $chanelList[$v->CateId] = ['id'=>$v->CateId,'text'=>$v->CateName,'num'=>0,'parent'=>"#",'state'=>['opened'=>true]];
        }

        $chanelList = array_values($chanelList);
        $this->assignconfig("channelList", $chanelList);

        $this->assign('type',$type);
        return $this->view->fetch();

    }

    /**
     * 添加
     */
    public function add()
    {
        $cateId = $this->request->get('cateId');
        $cateName = $this->request->get('cateName',"默认分组");
        $type = $this->request->get('type');

        if(empty($cateId)){
            $categoryModel = new \app\admin\model\yalimedia\Category();
            if(!$category = $categoryModel->where(['type'=>$type])->find()){
                exit;
            }else{
                $cateId = $category['cateid'];
            }
        }

        $yalimedia = get_addon_config('yalimedia');
        $config = $yalimedia['ali'];
        $regionId = $config['regionId'];

        $this->assign('cateId',$cateId);
        $this->assign('regionId',$regionId);
        $this->assign('cateName',$cateName);
        $this->assign('type',$type);

        $this->view->engine->layout(false);
        switch ($type){
            case "1":
                return $this->view->fetch("add_image");
                break;
            case "2":
            case "3":
                return $this->view->fetch();
        }

    }

    public function createUploadImage(){

        $titleName = $this->request->get("titleName");
        $cateId = $this->request->get("cateId");
        $result = AlibabaCloundHelper::instance()->createUploadImage($titleName,$cateId);

        if($result){
            echo json_encode(['UploadAddress'=>$result->UploadAddress,'ImageId'=>$result->ImageId,'RequestId'=>$result->RequestId,'UploadAuth'=>$result->UploadAuth]);
        }
        exit;
    }

    public function refreshUploadVideo(){
        $videoid = $this->request->get("videoid");

        $result = AlibabaCloundHelper::instance()->RefreshUploadVideo($videoid);
        if($result){
            echo json_encode(['UploadAddress'=>$result->UploadAddress,'VideoId'=>$result->VideoId,'RequestId'=>$result->RequestId,'UploadAuth'=>$result->UploadAuth]);
        }
        exit;
    }

    public function createUploadVideo(){

        $titleName = $this->request->get("titleName");
        $fileName = $this->request->get("fileName");
        $cateId = $this->request->get("cateId");


        $tmpid = "VOD_NO_TRANSCODE";

        $result = AlibabaCloundHelper::instance()->createUploadVideo($titleName,$fileName,$cateId,$tmpid);

        if($result){
            echo json_encode(['UploadAddress'=>$result->UploadAddress,'VideoId'=>$result->VideoId,'RequestId'=>$result->RequestId,'UploadAuth'=>$result->UploadAuth]);
        }
        exit;
    }


    public function tree(){

        $type = $this->request->get('type',2);
        $id = $this->request->get('id');

        if(empty($id) || $id == '#'){
            $categoryModel = new \app\admin\model\yalimedia\Category();
            if(!$category = $categoryModel->where(['type'=>$type])->find()){
                exit;
            }else{
                $cateId = $category['cateid'];
            }
        }else{
            $cateId = $id;
        }


        //查看当前是否已经生成根分类
        $list = AlibabaCloundHelper::instance()->categories($cateId);

        $chanelList = [];
        if($id=='#'){
            switch ($type){
                case "2":
                    $text = "全部音频";
                    break;
                case "3":
                    $text = "全部视频";
                    break;
            }
            $chanelList[$cateId] = ['id'=>$cateId,'type'=>'total','text'=>$text,'parent'=>"#"];
        }

        foreach($list as $k=>$v){
            if($v->SubTotal){
                $children = true;
            }else{
                $children = false;
            }
            $chanelList[$v->CateId] = ['id'=>$v->CateId,'text'=>$v->CateName,'type'=>"folder",'children'=>$children,'parent'=>$id=='#'?'#':$cateId,'state'=>['opened'=>false]];
        }

        $chanelList = array_values($chanelList);

        return json($chanelList);
    }

    /**
     * 素材上传分组
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function upload_tree(){
        $type = $this->request->get('type');
        $id = $this->request->get('id');

        if(empty($id) || $id == '#'){
            $categoryModel = new \app\admin\model\yalimedia\Category();
            if(!$category = $categoryModel->where(['type'=>$type])->find()){
                exit;
            }else{
                $cateId = $category['cateid'];
            }
        }else{
            $cateId = $id;
        }

        //查看当前是否已经生成根分类
        $list = AlibabaCloundHelper::instance()->categories($cateId);
        $chanelList = [];
        if($id=='#'){
            $chanelList[$cateId] = ['id'=>$cateId,'text'=>"默认分组",'type'=>'total','parent'=>"#",'state'=>['opened'=>true]];
        }
        foreach($list as $k=>$v){
            if($v->SubTotal){
                $children = true;
            }else{
                $children = false;
            }
            $chanelList[$v->CateId] = ['id'=>$v->CateId,'text'=>$v->CateName,'type'=>'folder','children'=>$children,'parent'=>$id=='#'?'#':$cateId,'state'=>['opened'=>false]];
        }
        $chanelList = array_values($chanelList);

        return json($chanelList);
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {

                    $Title = $params['title'];
                    $CateId = $params['cateid'];
                    $type = $params['type'];
                    if($type == 1){
                        $updateContent[] = ["ImageId"=>$ids,'Title'=>$Title,'CateId'=>$CateId];
                        $ret = AlibabaCloundHelper::instance()->update_image(json_encode($updateContent));
                    }else{
                        $ret = AlibabaCloundHelper::instance()->edit_video($ids,$CateId,$Title);
                    }

                    if($ret){
                        sleep(1);
                        $this->success();
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                } catch (ServerException $e){
                    $this->error("编辑失败，请检查阿里云服务");
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $type = $this->request->get("type");
        $row = (array)AlibabaCloundHelper::instance()->video($ids);

        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }



        $categoryModel = new \app\admin\model\yalimedia\Category();
        if(!$category = $categoryModel->where(['type'=>$type])->find()){
            exit;
        }else{
            $cateId = $category['cateid'];
        }


        if($cateId == $row['CateId']){
            $row['CateName'] = "默认分组";
        }


        //查看当前是否已经生成根分类
        $list = AlibabaCloundHelper::instance()->categories($cateId);

        $this->assign('type',$type);
        $this->assign('cateList',$list);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            try {
                $type = $this->request->get("type");

                if($type == 1){
                    $result = AlibabaCloundHelper::instance()->del_image($ids);
                }else{
                    $result = AlibabaCloundHelper::instance()->del_video($ids);
                }
                if($result){
                    sleep(1);
                    $this->success('请求成功');
                }else{
                    $this->error('删除失败');
                }
            }catch (ServerException $e){
                $this->error("删除失败，请检查阿里云服务");
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


}
